//inp 内容填充进去 - 现在的数据
import { reqGetUser,reqUpdateUser} from "../../api";

let updateForm = document.getElementById('userUpdateForm');
let usernameInp = document.getElementById('username');
let _idInp = document.getElementById('_id');
let profileInp = document.getElementById('profile');
let prevImg = document.getElementById('prevImg');

//拿到地址栏上的查询字符串信息
/* 
  读取query参数指定参数名的值
*/
function getQueryValue(name) {
    var str = location.href.split('?'); //['http://localhost:3009/userUpdate.html','id=63a134ddde4c94c593113813']
    var query = str[1]; //'id=63a134ddde4c94c593113813'
    var vars = query.split('&');//['id=63a134ddde4c94c593113813']
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=');//['id','63a134ddde4c94c593113813']
        if (pair[0] == name) { //'id' === 'id'
            return pair[1]; //'63a134ddde4c94c593113813'
        }
    }
}

//获取修改用户的id
let id = getQueryValue('id');

//去数据库获取原有数据
reqGetUser(id).then(({ data: { username, profile,_id } }) => {
    usernameInp.value = username;
    _idInp.value = _id;
    prevImg.src = 'http://localhost:8888' + profile;
})

//设置预览图
profileInp.onchange = function(e){
    // 读取文件对象
    let fileReader = new FileReader();
    // 获取文件
    let file = e.target.files[0];
    // 使用base64方式读取文件
    fileReader.readAsDataURL(file);
    // 当文件读取完毕
    fileReader.onload = function(){
        // 获取到 读取完成后的base64数据
       let profile =  fileReader.result;
       //将预览图片的src更新
       prevImg.src = profile;
    }
}

/* 
绑定提交事件
*/
updateForm.onsubmit = async (e) => {
    e.preventDefault()

    const formData = new FormData(updateForm)
    let result = await reqUpdateUser(formData)

    if (result.code === 2000) {
        alert('更新成功');
        window.location = '/users.html';
    }
}